package qdu.edu.cn.liu.store;

import redis.clients.jedis.Jedis;

import java.io.*;

public class StoreHyperlinkToRedisOrFile {
    private static final String HOST = "liu";
    private static final int REDIS_WRITE_PORT = 6381;
    private static final String HASH_HYPERLINK_KEY = "hash_hyperlink_key";
    private final Jedis jedis = new Jedis(HOST, REDIS_WRITE_PORT);
    private OutputStream outputStream = null;
    private OutputStreamWriter outputStreamWriter = null;
    private BufferedWriter bufferedWriter = null;

    public StoreHyperlinkToRedisOrFile() {
    }

    public void hashStoreToRedis(String words, String hyperlink) {
        jedis.hsetnx(HASH_HYPERLINK_KEY, words, hyperlink);
    }

    public BufferedWriter getBufferedWriter(String filePath) {
        try {
            if (outputStream == null) {
                outputStream = new FileOutputStream(filePath);
            }
            if (outputStreamWriter == null) {
                outputStreamWriter = new OutputStreamWriter(outputStream);
            }
            if (bufferedWriter == null) {
                bufferedWriter = new BufferedWriter(outputStreamWriter);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return bufferedWriter;
    }

    public void close() {
        jedis.close();
        try {
            if (bufferedWriter != null) {
                bufferedWriter.close();
            }
            if (outputStreamWriter != null) {
                outputStreamWriter.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}